package cn.aliang.cloud.hystrixorder.controller;

import cn.aliang.cloud.service.entity.ResultCode;
import cn.aliang.cloud.service.entity.ResultMessage;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: chendongliang
 * @Date: 2020/7/21 10:16
 *
 *
 * Controller 接口端实现服务降级
 * 使用HystrixCommond
 *
 */

@RestController
@RequestMapping("/order")
@DefaultProperties(defaultFallback = "payGlobalFallback")
public class OrderHystrixController {


    /*****
     *
     *
     * 一个接口对应一个降级回调方法
     * 需要降级的接口很多时，会导致回调接口增多，代码量爆炸
     *
     * 模拟：接口响应超过1秒 直接降级
     *
     */

    @GetMapping("/payTimeOut/{id}")
    @HystrixCommand(fallbackMethod = "payTimeOutFallback"
            ,commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000")
    })
    public ResultMessage<Void> payTimeOut(@PathVariable("id") String id ) throws InterruptedException {

        //线程睡3秒，模拟超时
        Thread.sleep(3000);

        return new ResultMessage<>(ResultCode.OK.getCode(),"接口正常");
    }

    public ResultMessage<Void> payTimeOutFallback(@PathVariable("id") String id ){

        return new ResultMessage<>(ResultCode.OK.getCode(),"接口超时---一对一fallback---服务降级");
    }


    /****
     *
     *
     *  采用全局降级回调方法
     *
     *
     */
    @GetMapping("/payTimeOut2/{id}")
    @HystrixCommand
    public ResultMessage<Void> payTimeOut2(@PathVariable("id") String id ){

        int a = 10/0;

        return new ResultMessage<>(ResultCode.OK.getCode(),"接口正常");
    }

    /***
     * 全局回调方法
     * @return
     */
    public ResultMessage<Void> payGlobalFallback(){

        return new ResultMessage<>(ResultCode.OK.getCode(),"接口超时---全局fallback---服务降级");

    }



}
